package com.dragon.www.haier.popupwindow;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.GradientDrawable;
import android.support.percent.PercentRelativeLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.dragon.www.haier.R;
import com.dragon.www.haier.activity.MainActivity;
import com.dragon.www.haier.adapter.SceneLampAdapter;
import com.dragon.www.haier.entity.ConferenceProfile;
import com.dragon.www.haier.entity.ConferenceProfileListInfo;
import com.dragon.www.haier.entity.Device;
import com.dragon.www.haier.entity.DeviceInfo;
import com.dragon.www.haier.entity.DeviceListInfo;
import com.dragon.www.haier.entity.Room;
import com.dragon.www.haier.entity.ScenceInfo;
import com.dragon.www.haier.entity.ServiceResult;
import com.dragon.www.haier.net.NetHelper;
import com.dragon.www.haier.net.NetUtils;
import com.dragon.www.haier.view.dialog.RoomPickDialog;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by daiye on 2016/6/3.
 */
public class ConferenceSetPopWindowEx  extends BasePopupWindow implements RadioGroup.OnCheckedChangeListener {
    private final static int ConferencePopBackgroundColor = 0xD9FF7200;
    private ImageView imageBackConference;
    private RadioGroup radioGroup_devicetype;
    private PercentRelativeLayout devices_settingcontent;
    private LinearLayout mSettingLl;
    private LinearLayout mSettingL2;
    private LinearLayout mSettingL3;
    private LinearLayout mSettingL4;
    private LinearLayout mSettingL5;
    private TextView mTemperatureTv;
    private TextView mTemperatureReduce;
    private TextView mTemperatureAdd;
    private RadioGroup mAirWindModeRg;
    private RadioGroup mAirWindSpeedRg;
    private RadioGroup mAirWindPowerRg;
    private RadioGroup mCurtainValueRg;
    private RadioGroup mWindSystemValueRg;
    private RadioGroup mHumidifierValueRg;
    private Button mSaveBtCurtain;
    private Button mSaveBtAir;
    private Button mSaveBtWindSystem;
    private Button mSaveBtHumidifier;
    private Button mSaveBtLamp;
    private Button mOpenAllBt;
    private Button mCloseAllBt;
    private List<Device> mDevices = null;

    private String mDeviceSelectedType = MainActivity.TYPE_LAMP;  //选中的设备类型

    private int mRoomSelectedItem = -1;                         //选中的房间索引

    private List<Room> mRooms = null;                           //总的房间列表
    private List<Room> mSelectedRooms  = new ArrayList<>();     //情景模式下选中的房间
    private RoomSelectedAdapter mRoomSelectedAdapter;           //选中的房间显示适配器
    private ListView mRoomsListView = null;

    private HashMap<String, List<ConferenceProfile>> mConferenceProfilesMap = new HashMap<String, List<ConferenceProfile>>();    //情景模式下选中的设备,对应房间设备key—object

    private RoomPickDialog mRoomPickDialog = null;

    public ConferenceSetPopWindowEx(Context context) {
        super(context);
    }

    public void showPopWindow(View view, int xOffsetToView, int yOffsetToView) {
        contentView = LayoutInflater.from(context).inflate(R.layout.conference_setting_ex, null);
        super.showPopWindow(view, xOffsetToView, yOffsetToView);
        imageBackConference = (ImageView) contentView.findViewById(R.id.image_back_setting);
        imageBackConference.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        mOpenAllBt = (Button)contentView.findViewById(R.id.openall_bt);
        mOpenAllBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAllDevice();
            }
        });
        mCloseAllBt = (Button)contentView.findViewById(R.id.closeall_bt);
        mCloseAllBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeAllDevice();
            }
        });

        devices_settingcontent = (PercentRelativeLayout) contentView.findViewById(R.id.devices_settingcontent);
        mSettingLl = (LinearLayout)contentView.findViewById(R.id.setting_ll);
        mTemperatureTv = (TextView)contentView.findViewById(R.id.tv_aircondition_tem);
        mTemperatureReduce = (TextView)contentView.findViewById(R.id.tv_tem_reduce);
        mTemperatureReduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int temp = Integer.parseInt(mTemperatureTv.getText().toString())-1;
                if(temp >= 17)
                    mTemperatureTv.setText(String.valueOf(temp));
            }
        });
        mTemperatureAdd = (TextView)contentView.findViewById(R.id.tv_tem_add);
        mTemperatureAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int temp = Integer.parseInt(mTemperatureTv.getText().toString())+1;
                if(temp <= 30)
                    mTemperatureTv.setText(String.valueOf(temp));
            }
        });
        mSaveBtCurtain = (Button)contentView.findViewById(R.id.save_bt_curtain);
        mSaveBtCurtain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int curtainDeviceValue = -1;
                int checkcurtainId = mCurtainValueRg.getCheckedRadioButtonId();
                switch(checkcurtainId){
                    case R.id.rb_curtain_up:
                        curtainDeviceValue = 2;
                        break;
                    case R.id.rb_curtain_down:
                        curtainDeviceValue = 1;
                        break;
                }
                saveCurtainParameterForSelectedDevice(curtainDeviceValue);
            }

        });
        mSaveBtLamp = (Button)contentView.findViewById(R.id.save_bt_lamp);
        mSaveBtLamp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List lampDevicePower = mAdapter.getlamppower() ;
                saveLampParameterForSelectedDevice(lampDevicePower);
            }
        });
        mSaveBtWindSystem = (Button)contentView.findViewById(R.id.save_bt_wind_system);
        mSaveBtWindSystem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int windsystemDeviceValue = -1;
                int checkwindsystemId = mWindSystemValueRg.getCheckedRadioButtonId();
                switch(checkwindsystemId){
                    case R.id.rb_wind_system_open:
                        windsystemDeviceValue = 1;
                        break;
                    case R.id.rb_wind_system_close:
                        windsystemDeviceValue = 0;
                        break;
                }
                savewindsystemParameterForSelectedDevice(windsystemDeviceValue);
            }
        });
        mSaveBtHumidifier = (Button)contentView.findViewById(R.id.save_bt_humidifier);
        mSaveBtHumidifier.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int humidifierDeviceValue = -1;
                int checkhumidifierId = mHumidifierValueRg.getCheckedRadioButtonId();
                switch(checkhumidifierId){
                    case R.id.rb_humidifier_open:
                        humidifierDeviceValue = 1;
                        break;
                    case R.id.rb_humidifier_close:
                        humidifierDeviceValue = 0;
                        break;
                }
                savehumidifierParameterForSelectedDevice(humidifierDeviceValue);
            }
        });
        mSaveBtAir = (Button)contentView.findViewById(R.id.save_bt_air);
        mSaveBtAir.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int mode = -1;
                int speed = -1;
                int power = -1;
                int temp = Integer.parseInt(mTemperatureTv.getText().toString());
                int checkModeId = mAirWindModeRg.getCheckedRadioButtonId();
                switch(checkModeId){
                    case R.id.rb_mode_airy:
                        mode = 1;
                        break;
                    case R.id.rb_mode_heat:
                        mode = 2;
                        break;
                    case R.id.rb_mode_cold:
                        mode = 3;
                        break;
                    case R.id.rb_mode_dehumidify:
                        mode = 4;
                        break;
                    case R.id.rb_mode_auto:
                        mode = 0;
                        break;
                }
                int checkSpeedId = mAirWindSpeedRg.getCheckedRadioButtonId();
                switch(checkSpeedId){
                    case R.id.rb_speed_low:
                        speed = 1;
                        break;
                    case R.id.rb_speed_mid:
                        speed = 2;
                        break;
                    case R.id.rb_speed_high:
                        speed = 3;
                        break;
                    case R.id.rb_speed_auto:
                        speed = 0;
                        break;
                }
                int checkPowerId = mAirWindPowerRg.getCheckedRadioButtonId();
                switch(checkPowerId){
                    case R.id.rb_power_open:
                        power = 1;
                        break;
                    case R.id.rb_power_close:
                        power = 0;
                        break;
                }
                saveAirParameterForSelectedDevice(temp, mode, speed, power);
            }
        });

        mSettingL2 = (LinearLayout)contentView.findViewById(R.id.setting_l2);
        mSettingL3 = (LinearLayout)contentView.findViewById(R.id.setting_l3);
        mSettingL4 = (LinearLayout)contentView.findViewById(R.id.setting_l4);
        mSettingL5 = (LinearLayout)contentView.findViewById(R.id.setting_l5);
        mAirWindModeRg = (RadioGroup) contentView.findViewById(R.id.radioGroup_wind_mode);
        mAirWindSpeedRg = (RadioGroup) contentView.findViewById(R.id.radioGroup_wind_speed);
        mAirWindPowerRg = (RadioGroup) contentView.findViewById(R.id.radioGroup_power);
        mCurtainValueRg = (RadioGroup) contentView.findViewById(R.id.radioGroup_curtain);
        mWindSystemValueRg = (RadioGroup) contentView.findViewById(R.id.radioGroup_wind_system);
        mHumidifierValueRg = (RadioGroup) contentView.findViewById(R.id.radioGroup_humidifier);
        radioGroup_devicetype = (RadioGroup)contentView.findViewById(R.id.radioGroup_devicetype);
        radioGroup_devicetype.setOnCheckedChangeListener(this);

        //防黑边
        this.setBackgroundDrawable(new BitmapDrawable());
        //显示
        GradientDrawable myGrad = (GradientDrawable) contentView.getBackground();
        myGrad.setColor(ConferencePopBackgroundColor);
        //防止虚拟软键盘被弹出菜单遮住
        this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        gview = (GridView)contentView.findViewById(R.id.gview1);
        mRoomsListView = (ListView)contentView.findViewById(R.id.rooms_list);
        mRoomSelectedAdapter = new RoomSelectedAdapter(context);
        mRoomsListView.setAdapter(mRoomSelectedAdapter);
        mRoomsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //增加新房间
                if (mRooms != null) {
                    if (position == mSelectedRooms.size()) {
                        mRoomPickDialog = new RoomPickDialog(context);
                        mRoomPickDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        mRoomPickDialog.setRooms(mRooms);
                        mRoomPickDialog.show();
                        mRoomPickDialog.setLisntener(new RoomPickDialog.OnSelectListener() {
                            @Override
                            public void addRoom(Room room) {
                                if (!isRoomAdded(room.getRoomid())) {
                                    addRoomToProfiles(room);
                                    refreshSelectedRoom();
                                } else {
                                    Toast.makeText(context, "已经添加过该房间了，不能重复添加！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    } else {
                        //选择某个房间在此基础上修改该房间下设备的参数
                        mRoomSelectedItem = position;
                        refreshSelectedRoom();
                        setRoomId(mSelectedRooms.get(mRoomSelectedItem).getRoomid());
                        getRoomDeviceFromNetwork(mSelectedRooms.get(mRoomSelectedItem));
                        refreshSelectedProfilesInSelectedRoom();

                    }
                }
            }
        });
        //从网络同步情景模式下的设备列表到本地
        pulldown();
    }

    public void getRoomDeviceFromNetwork(final Room selectRoom){
        if( selectRoom != null ){
            NetHelper.getDevices(context, selectRoom.getRoomid(), new NetUtils.NetCallBack<ServiceResult>() {
                @Override
                public void success(ServiceResult rspData) {
                    if (rspData.getCode().equals("0000")) {
                        final DeviceListInfo deviceListInfo = (DeviceListInfo) rspData;
                        mDevices = deviceListInfo.getDevices();
                        setDevices(mDevices);
                        mAdapter = new SceneLampAdapter(context);
                        mAdapter.setData(getData(MainActivity.TYPE_LAMP));
                        mDeviceSelectedType = MainActivity.TYPE_LAMP;
                        refreshSelectedProfilesInSelectedRoom();
                        setDeviceParameterForSelectedDevice();
                        radioGroup_devicetype.check(R.id.setting_lamp);
                    }else{
                        Toast.makeText(context, "获取房间中的设备失败，原因"+rspData.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void failed(String msg) {
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                }
            }, DeviceListInfo.class);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.setting_lamp:
                mDeviceSelectedType = MainActivity.TYPE_LAMP;
                refreshSelectedProfilesInSelectedRoom();
                setDeviceParameterForSelectedDevice();
                break;
            case R.id.setting_air:
                mDeviceSelectedType = "2";
                refreshSelectedProfilesInSelectedRoom();
                setDeviceParameterForSelectedDevice();
                break;
            case R.id.setting_curtain:
                mDeviceSelectedType = "3";
                refreshSelectedProfilesInSelectedRoom();
                setDeviceParameterForSelectedDevice();
                break;
            case R.id.setting_wind_system:
                mDeviceSelectedType = "4";
                refreshSelectedProfilesInSelectedRoom();
                setDeviceParameterForSelectedDevice();
                break;
            case R.id.setting_humidifier:
                mDeviceSelectedType = "5";
                refreshSelectedProfilesInSelectedRoom();
                setDeviceParameterForSelectedDevice();
                break;
            case R.id.setting_plantwall:
                mDeviceSelectedType = MainActivity.TYPE_PLANTWALL;
                refreshSelectedProfilesInSelectedRoom();
                break;
        }
    }

    /**
     * 从网络获取房间后设置对应的app设备,会议场景所定义的房间从这个集合中选择
     * 2016/06/01
     */
    public void setRooms(List<Room> rooms){
        this.mRooms = rooms;
    }

    /**
     * 是否在情景模式中已经添加过该房间
     * 2016/06/01
     */
    private boolean isRoomAdded(int roomId){
        boolean is = false;
        for(int i = 0; i < mSelectedRooms.size(); i++)
        {
            if( mSelectedRooms.get(i).getRoomid() == roomId )
            {
                is = true;
                break;
            }
        }
        return is;
    }

    /**
     * 将某个房间添加到情景列表中
     * 2016/06/01
     */
    private void addRoomToProfiles(Room room){
        mSelectedRooms.add(room);
        List<ConferenceProfile> profiles = new ArrayList<>();
        int roomId = room.getRoomid();
        if(!mConferenceProfilesMap.containsKey(String.valueOf(roomId))){
            for(int i = 0; i < 6; i++){
                ConferenceProfile profile = new ConferenceProfile();
                profile.setType(String.valueOf(i+1));
                profile.setStatus(0);
                profiles.add(profile);
            }
            mConferenceProfilesMap.put(String.valueOf(roomId), profiles);
        }
        synchronous();
    }

    private void deleteDeviceInProfiles(){
        ConferenceProfile airProfile = getSelectedProfilesInSelectedRoom();
        if(airProfile.getStatus() == 0 )
            airProfile.setStatus(1);
        else
            airProfile.setStatus(0);
        synchronous();
        refreshSelectedProfilesInSelectedRoom();
    }

    private String getDeviceTypeName(){
        String s = "";
        if(mDeviceSelectedType.equals(MainActivity.TYPE_LAMP)){
            s = "灯光设备";
        }else if(mDeviceSelectedType.equals("2")){
            s = "空调设备";
        }else if(mDeviceSelectedType.equals("3")){
            s = "窗帘设备";
        }else if(mDeviceSelectedType.equals("4")){
            s = "清风系统";
        }else if(mDeviceSelectedType.equals("5")){
            s = "灯加湿器备";
        }else if(mDeviceSelectedType.equals(MainActivity.TYPE_PLANTWALL)){
            s = "植物墙设备";
        }
        return s;
    }

    private void setDeviceParameterForSelectedDevice(){
        if( mDeviceSelectedType.equals("3")){
            ConferenceProfile curtainProfile = getSelectedProfilesInSelectedRoom();
            if (curtainProfile != null){
                int curtainDeviceValue = curtainProfile.curtainDeviceValue;
                switch(curtainDeviceValue){
                    case 2:
                        mCurtainValueRg.check(R.id.rb_curtain_up);
                        break;
                    case 1:
                        mCurtainValueRg.check(R.id.rb_curtain_down);
                        break;
                }
            }
        }
        if( mDeviceSelectedType.equals("4")){
            ConferenceProfile windsystemProfile = getSelectedProfilesInSelectedRoom();
            if (windsystemProfile != null){
                int windsystemDeviceValue = windsystemProfile.windsystemDeviceValue;
                switch(windsystemDeviceValue){
                    case 1:
                        mWindSystemValueRg.check(R.id.rb_wind_system_open);
                        break;
                    case 0:
                        mWindSystemValueRg.check(R.id.rb_wind_system_close);
                        break;
                }
            }
        }
        if( mDeviceSelectedType.equals("5")){
            ConferenceProfile humidifierProfile = getSelectedProfilesInSelectedRoom();
            if (humidifierProfile != null){
                int humidifierDeviceValue = humidifierProfile.humidifierDeviceValue;
                switch(humidifierDeviceValue){
                    case 1:
                        mHumidifierValueRg.check(R.id.rb_humidifier_open);
                        break;
                    case 0:
                        mHumidifierValueRg.check(R.id.rb_humidifier_close);
                        break;
                }
            }
        }
        if( mDeviceSelectedType.equals(MainActivity.TYPE_LAMP)  ){
            ConferenceProfile lampProfile = getSelectedProfilesInSelectedRoom();
            if (lampProfile != null) {
                List<int[]> lamppower = lampProfile.lampDevicePower;
                if (lamppower == null){
                    lamppower = new ArrayList<int[]>();
                    lamppower.add(new int[]{0,0,0,0});
                    lamppower.add(new int[]{0,0,0,0});
                }
                mAdapter = new SceneLampAdapter(context);
                mAdapter.setData(getData(MainActivity.TYPE_LAMP));
                mAdapter.setlamppower(lamppower);
                gview.setAdapter(mAdapter);
                getValue("relay");
            }
        }
        if( mDeviceSelectedType.equals("2")  ) {
            ConferenceProfile airProfile = getSelectedProfilesInSelectedRoom();
            if (airProfile != null) {
                int temp = airProfile.airDeviceTemp;
                int mode = airProfile.airDeviceMode;
                int speed = airProfile.airDeviceSpeed;
                int power = airProfile.airDevicePower;
                if (temp > 30) {
                    temp = 30;
                } else if (temp < 17) {
                    temp = 17;
                }
                mTemperatureTv.setText(String.valueOf(temp));
                switch (mode) {
                    case 1:
                        mAirWindModeRg.check(R.id.rb_mode_airy);
                        break;
                    case 2:
                        mAirWindModeRg.check(R.id.rb_mode_heat);
                        break;
                    case 3:
                        mAirWindModeRg.check(R.id.rb_mode_cold);
                        break;
                    case 4:
                        mAirWindModeRg.check(R.id.rb_mode_dehumidify);
                        break;
                    case 0:
                        mAirWindModeRg.check(R.id.rb_mode_auto);
                        break;
                }
                switch (speed) {
                    case 1:
                        mAirWindSpeedRg.check(R.id.rb_speed_low);
                        break;
                    case 2:
                        mAirWindSpeedRg.check(R.id.rb_speed_mid);
                        break;
                    case 3:
                        mAirWindSpeedRg.check(R.id.rb_speed_high);
                        break;
                    case 0:
                        mAirWindSpeedRg.check(R.id.rb_speed_auto);
                        break;
                }
                switch (power) {
                    case 1:
                        mAirWindPowerRg.check(R.id.rb_power_open);
                        break;
                    case 0:
                        mAirWindPowerRg.check(R.id.rb_power_close);
                        break;
                }
            }
        }
    }

    private void saveAirParameterForSelectedDevice(int temp, int mode, int speed,int power){
        mDeviceSelectedType = "2";
        ConferenceProfile airProfile = getSelectedProfilesInSelectedRoom();
        if (airProfile != null){
            airProfile.airDeviceMode = mode;
            airProfile.airDeviceSpeed = speed;
            airProfile.airDeviceTemp = temp;
            airProfile.airDevicePower = power;
            synchronous();
        }
    }

    private void saveLampParameterForSelectedDevice(List<int[]> lamppower){
        mDeviceSelectedType = MainActivity.TYPE_LAMP;
        ConferenceProfile lampProfile = getSelectedProfilesInSelectedRoom();
        if (lampProfile != null){
            lampProfile.lampDevicePower = lamppower;
            synchronous();
        }
    }

    private void saveCurtainParameterForSelectedDevice(int curtainDeviceValue){
        mDeviceSelectedType = "3";
        ConferenceProfile curtainProfile = getSelectedProfilesInSelectedRoom();
        if (curtainProfile != null){
            curtainProfile.curtainDeviceValue = curtainDeviceValue;
        synchronous();
        }
    }

    private void savewindsystemParameterForSelectedDevice(int windsystemDeviceValue){
        mDeviceSelectedType = "4";
        ConferenceProfile windsystemProfile = getSelectedProfilesInSelectedRoom();
        if (windsystemProfile != null){
            windsystemProfile.windsystemDeviceValue = windsystemDeviceValue;
            synchronous();
        }
    }

    private void savehumidifierParameterForSelectedDevice(int humidifierDeviceValue){
        mDeviceSelectedType = "5";
        ConferenceProfile humidifierProfile = getSelectedProfilesInSelectedRoom();
        if (humidifierProfile != null){
            humidifierProfile.humidifierDeviceValue = humidifierDeviceValue;
            synchronous();
        }
    }

    /**
     * 
     * 2016/06/01
     */
    private ConferenceProfile getSelectedProfilesInSelectedRoom(){
        ConferenceProfile profile = null;
        if( mRoomSelectedItem != -1 ){
            int roomId = mSelectedRooms.get(mRoomSelectedItem).getRoomid();
            if(mConferenceProfilesMap.containsKey(String.valueOf(roomId))){
                List<ConferenceProfile> profilesList = mConferenceProfilesMap.get(String.valueOf(roomId));
                for(int i=0;i<profilesList.size();i++){
                    if(profilesList.get(i).getType().equals(mDeviceSelectedType)){
                        profile = profilesList.get(i);
                        break;
                    }
                }
            }
        }
        return profile;
    }

    /**
     * 刷新选择的房间列表
     * 2016/06/01
     */
    private void refreshSelectedRoom(){
        mRoomSelectedAdapter.notifyDataSetChanged();
    }

    /**
     * 当选择了某个房间或者点击了不同的设备类型后刷新具体的设备列表
     * 2016/06/01
     */
    private void refreshSelectedProfilesInSelectedRoom(){
        ConferenceProfile profile = getSelectedProfilesInSelectedRoom();
        if (profile != null){
            if(profile.getType().equals(mDeviceSelectedType)){
                devices_settingcontent.setVisibility(View.VISIBLE);
                if( mDeviceSelectedType.equals("2") ){
                    mSettingLl.setVisibility(View.VISIBLE);
                    mSettingL2.setVisibility(View.GONE);
                    mSettingL3.setVisibility(View.GONE);
                    mSettingL4.setVisibility(View.GONE);
                    mSettingL5.setVisibility(View.GONE);
                }else if( mDeviceSelectedType.equals(MainActivity.TYPE_LAMP) ){
                    mSettingL2.setVisibility(View.VISIBLE);
                    mSettingLl.setVisibility(View.GONE);
                    mSettingL3.setVisibility(View.GONE);
                    mSettingL4.setVisibility(View.GONE);
                    mSettingL5.setVisibility(View.GONE);
                }else if( mDeviceSelectedType.equals("3") ){
                    mSettingL2.setVisibility(View.GONE);
                    mSettingLl.setVisibility(View.GONE);
                    mSettingL3.setVisibility(View.VISIBLE);
                    mSettingL4.setVisibility(View.GONE);
                    mSettingL5.setVisibility(View.GONE);
                }else if( mDeviceSelectedType.equals("4") ){
                    mSettingL2.setVisibility(View.GONE);
                    mSettingLl.setVisibility(View.GONE);
                    mSettingL3.setVisibility(View.GONE);
                    mSettingL4.setVisibility(View.VISIBLE);
                    mSettingL5.setVisibility(View.GONE);
                }else if( mDeviceSelectedType.equals("5") ){
                    mSettingL2.setVisibility(View.GONE);
                    mSettingLl.setVisibility(View.GONE);
                    mSettingL3.setVisibility(View.GONE);
                    mSettingL4.setVisibility(View.GONE);
                    mSettingL5.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    /**
     * 把情景模式中的所有设备打开
     * 2016/06/01
     */
    private void openAllDevice(){
//        Iterator iter = mConferenceProfilesMap.entrySet().iterator();
//        while (iter.hasNext()) {
//            Map.Entry entry = (Map.Entry) iter.next();
//            String key = (String) entry.getKey();
//            List<Device> val = (List<Device>) entry.getValue();
//        }
//        int curtainDeviceValue = -1;
        mDeviceSelectedType = MainActivity.TYPE_LAMP;
        ConferenceProfile lampProfile = getSelectedProfilesInSelectedRoom();
        List<int[]> lamppower = new ArrayList<int[]>();
        if (lampProfile != null){
            lamppower = lampProfile.lampDevicePower;
        }else{
            lamppower.add(new int[]{0,0,0,0});
            lamppower.add(new int[]{0,0,0,0});
        }
        if (lamppower == null) {
            lamppower = new ArrayList<int[]>();
            lamppower.add(new int[]{0,0,0,0});
            lamppower.add(new int[]{0,0,0,0});
        }
        mDeviceSelectedType = "2";
        ConferenceProfile airProfile = getSelectedProfilesInSelectedRoom();
        int temp = 25;
        int mode = 0;
        int speed = 0;
        int power = 0;
        List<Integer> air = new ArrayList<>();
        if (airProfile != null){
            temp = airProfile.airDeviceTemp;
            mode = airProfile.airDeviceMode;
            speed = airProfile.airDeviceSpeed;
            power = airProfile.airDevicePower;
        }
        air.add(power);
        air.add(mode);
        air.add(speed);
        air.add(temp);
        mDeviceSelectedType = "3";
        ConferenceProfile curtainProfile = getSelectedProfilesInSelectedRoom();
        int curtainDeviceValue = 2;
        if (curtainProfile != null) {
            curtainDeviceValue  = curtainProfile.curtainDeviceValue;
        }
        mDeviceSelectedType = "4";
        ConferenceProfile windsystemProfile = getSelectedProfilesInSelectedRoom();
        int windsystemDeviceValue = 0;
        if (windsystemProfile != null) {
            windsystemDeviceValue  = windsystemProfile.windsystemDeviceValue;
        }
        mDeviceSelectedType = "5";
        ConferenceProfile humidifierProfile = getSelectedProfilesInSelectedRoom();
        int humidifierDeviceValue = 0;
        if (humidifierProfile != null) {
            humidifierDeviceValue  = humidifierProfile.humidifierDeviceValue;
        }

        List<Device> LAMPS = getData(MainActivity.TYPE_LAMP);
        int box1 = -1;
        int box2 = -1;
        Boolean ifbox1 = false;
        Boolean ifbox2 = false;
        List<Device> box1devices = new ArrayList<>();
        List<Device> box2devices = new ArrayList<>();
        if (LAMPS.size() != 0 ){
            box1 = Integer.parseInt(LAMPS.get(0).getequipNo().split("-")[0]);
            ifbox1 = true;

            for( int i= 0; i < LAMPS.size(); i++ ){
                if (  Integer.parseInt(LAMPS.get(i).getequipNo().split("-")[0])==box1){
                    box1devices.add(LAMPS.get(i));
                }
            }
            for (Device x : LAMPS) {

                if (Integer.parseInt(x.getequipNo().split("-")[0]) != box1){
                     box2 = Integer.parseInt(x.getequipNo().split("-")[0]);
                     ifbox2 = true;

                    for( int i= 0; i < LAMPS.size(); i++ ){
                        if (  Integer.parseInt(LAMPS.get(i).getequipNo().split("-")[0])==box2){
                            box2devices.add(LAMPS.get(i));
                        }
                    }
                }
            }
        }
        if (ifbox1) {
            NetHelper.sendscene(context, box1, 0, 1, air, curtainDeviceValue, lamppower, box1devices,windsystemDeviceValue,humidifierDeviceValue, new NetUtils.NetCallBack<DeviceInfo>() {

                @Override
                public void success(DeviceInfo rspData) {
                    if (rspData.getError() == 0) {
                        Log.e("请求成功", "初始化成功");
                    } else {
                        String DD = rspData.getDescription();
                        Log.e("错误描述", DD);
                    }
                }

                @Override
                public void failed(String msg) {
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                }
            }, DeviceInfo.class);
        }
        if (ifbox2){
            NetHelper.sendscene(context, box2, 1, 1, air, curtainDeviceValue, lamppower, box2devices,windsystemDeviceValue,humidifierDeviceValue, new NetUtils.NetCallBack<DeviceInfo>() {

                @Override
                public void success(DeviceInfo rspData) {
                    if (rspData.getError() == 0) {
                        Log.e("请求成功", "初始化成功");
                    } else {
                        String DD = rspData.getDescription();
                        Log.e("错误描述", DD);
                    }
                }

                @Override
                public void failed(String msg) {
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                }
            }, DeviceInfo.class);
        }
    }

    /**
     * 把情景模式中的所有设备关闭
     * 2016/06/01
     */
    private void closeAllDevice(){
//        Iterator iter = mConferenceProfilesMap.entrySet().iterator();
//        while (iter.hasNext()) {
//            Map.Entry entry = (Map.Entry) iter.next();
//            String key = (String) entry.getKey();
//            List<Device> val = (List<Device>) entry.getValue();
//        }
        NetHelper.sendall(context, String.valueOf(getRoomId()), 1, 0, new NetUtils.NetCallBack<DeviceInfo>() {
            @Override
            public void success(DeviceInfo rspData) {
                if (rspData.getError()== 0) {
                    Log.e("全关", "操作成功");
                } else {
                    String DD = rspData.getDescription();
                    Log.e("错误描述", DD);
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        }, DeviceInfo.class);
    }

    /**
     * 同步设置的情景模式设备到服务器(遍历mConferenceProfilesMap然后上传)
     * 2016/06/01
     */
    private void  synchronous(){
        if( mConferenceProfilesMap != null ){
            //构建房间集合体
            List<Map<String, Object>> roomlists = new ArrayList<>();
            Iterator iter = mConferenceProfilesMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String)entry.getKey();
                List<ConferenceProfile> val = (List<ConferenceProfile>)entry.getValue();
                if( val.size() != 0 ){
                    //构建每个房间的map结构体
                    Map<String, Object> mapRooms = new HashMap<>();
                    List<Map<String, Object>> profilelists = new ArrayList<>();
                    for(int i = 0; i < val.size(); i++ ){
                        //构建每个设备的map结构体
                        ConferenceProfile profile = val.get(i);
                        Map<String, Object> mapDevice = new HashMap<>();
                        mapDevice.put("status", profile.getStatus());
                        mapDevice.put("equipType", profile.getType());
                        if(profile.getType().equals("2")) {
                            mapDevice.put("airDeviceTemp", profile.airDeviceTemp);
                            mapDevice.put("airDeviceMode", profile.airDeviceMode);
                            mapDevice.put("airDeviceSpeed", profile.airDeviceSpeed);
                            mapDevice.put("airDevicePower", profile.airDevicePower);
                        }else if (profile.getType().equals(MainActivity.TYPE_LAMP)){
                            mapDevice.put("lampDevicePower", profile.lampDevicePower);
                        }else if (profile.getType().equals("3")){
                            mapDevice.put("curtainDeviceValue", profile.curtainDeviceValue);
                        } else if (profile.getType().equals("4")){
                            mapDevice.put("windsystemDeviceValue", profile.windsystemDeviceValue);
                        } else if (profile.getType().equals("5")){
                            mapDevice.put("humidifierDeviceValue", profile.humidifierDeviceValue);
                        }
                        profilelists.add(mapDevice);
                    }
                    mapRooms.put("infoList",profilelists);
                    mapRooms.put("roomId",key);
                    roomlists.add(mapRooms);
                }
            }

            NetHelper.updateScene(context, roomlists, new NetUtils.NetCallBack<ServiceResult>() {
                @Override
                public void success(ServiceResult rspData) {
                    if (rspData.getCode().equals("0000")) {
                        Toast.makeText(context, "场景已和服务器同步完成！", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(context, "场景同步失败，原因"+rspData.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void failed(String msg) {
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                }
            }, ServiceResult.class);
        }
    }

    /**
     * 从服务器下载同步情景模式设备到本地(同步设备列表到mConferenceProfilesMap)
     * 2016/06/01
     */
    private void  pulldown(){
        NetHelper.getScene(context, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getCode().equals("0000")) {
                    ScenceInfo scenceInfo = (ScenceInfo) rspData;
                    String str = scenceInfo.getContent();
                    try {
                        Gson gson = new Gson();
                        ConferenceProfileListInfo roomProfileListInfo = gson.fromJson(str, ConferenceProfileListInfo.class);
                        List<ConferenceProfileListInfo.ProfileList> roomProfileList = roomProfileListInfo.getData();
                        for (int i = 0; i < roomProfileList.size(); i++) {
                            ConferenceProfileListInfo.ProfileList roomProfile = roomProfileList.get(i);
                            String roomId = roomProfile.getRoomId();
                            List<ConferenceProfile> profiles = roomProfile.getProfiles();
                            mConferenceProfilesMap.put(roomId, profiles);
                            //从网络获取的配置设置到本地
                            if (mRooms != null) {
                                for (int a = 0; a < mRooms.size(); a++) {
                                    Room room = mRooms.get(a);
                                    if (room.getRoomid() == Integer.parseInt(roomId)) {
                                        mSelectedRooms.add(room);
                                    }
                                }
                            }
                            //始终默认选择第一个room
                            mRoomSelectedItem = 0;
                        }
                        setRoomId(mSelectedRooms.get(mRoomSelectedItem).getRoomid());
                        getRoomDeviceFromNetwork(mSelectedRooms.get(mRoomSelectedItem));
                        refreshSelectedRoom();
                        refreshSelectedProfilesInSelectedRoom();
                        Toast.makeText(context, "场景同步到本地完成！", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
                    }
                } else if (rspData.getCode().equals("0001")) {
                    Toast.makeText(context, "服务器上暂时还没有保存有会议配置！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "场景同步失败，原因" + rspData.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        }, ScenceInfo.class);
    }

    /**
     * 房间列表适配器
     * 2016/06/01
     */
    public class RoomSelectedAdapter extends BaseAdapter {
        public class RoomViewHolder {
            public TextView tv_room;
            public View v_select;
        }

        private Context mcontext;

        public RoomSelectedAdapter(Context context) {
            mcontext = context;
        }

        @Override
        public int getCount() {
            return mSelectedRooms.size()+1;
        }

        @Override
        public Object getItem(int position) {
            if(position < mSelectedRooms.size())
                return mSelectedRooms.get(position);
            else
                return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            RoomViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new RoomViewHolder();
                convertView = LayoutInflater.from(mcontext).inflate(R.layout.room_selected_item, parent, false);
                viewHolder.tv_room = (TextView) convertView.findViewById(R.id.tv_room);
                viewHolder.v_select = convertView.findViewById(R.id.select_v);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (RoomViewHolder) convertView.getTag();
            }
            if(position < mSelectedRooms.size()){
                final Room room = mSelectedRooms.get(position);
                if( mRoomSelectedItem !=-1 && mRoomSelectedItem == position){
                    viewHolder.v_select.setVisibility(View.GONE);
                }else{
                    viewHolder.v_select.setVisibility(View.VISIBLE);
                }
                viewHolder.tv_room.setText(room.getRoomName());
            }else{
                viewHolder.v_select.setVisibility(View.VISIBLE);
                viewHolder.tv_room.setText("+");
            }
            return convertView;
        }
    }
}
